var combinationDrag = document.getElementById("combinationDrag");
var combinationDiv = document.getElementById("combination");
startDrag(combinationDrag, combinationDiv);
jsPlumb.ready(function() {
    var combination = $("#combination");
    var content = $("#content");
    var instance = window.jsp = jsPlumb.getInstance({
        // default drag options
        DragOptions: { cursor: 'pointer', zIndex: 2000 },
        // the overlays to decorate each connection with.  note that the label overlay uses a function to generate the label text; in this
        // case it returns the 'labelText' member that we set on each connection in the 'init' method below.
        ConnectionOverlays: [
            [ "Arrow", {
                location: 1,
                visible:true,
                width:11,
                id:"ARROW",
                length:11
            } ],
            [ "Label", {
                location: 0.1,
                id: "label",
                cssClass: "aLabel",
                events:{
                }
            }]
        ],
        Container: "canvas"
    });
// this is the paint style for the connecting lines..
    var connectorPaintStyle = {
            strokeWidth: 2,
            stroke: "#61B7CF",
            joinstyle: "round",
            outlineStroke: "white",
            outlineWidth: 2
        },
        // .. and this is the hover style.
        connectorHoverStyle = {
            strokeWidth: 3,
            stroke: "#61B7CF",
            outlineWidth: 5,
            outlineStroke: "white"
        },
        endpointHoverStyle = {
            fill: "#61B7CF",
            stroke: "#61B7CF"
        },
        // the definition of source endpoints (the small blue ones)
        sourceEndpoint = {
            endpoint: "Dot",
            paintStyle: {
                stroke: "#61B7CF",
                fill: "transparent",
                radius: 5,
                strokeWidth: 1
            },
            isSource: true,
            connector: [ "Flowchart", { stub: [10, 20], gap: 10, cornerRadius: 5, alwaysRespectStubs: true } ],
            connectorStyle: connectorPaintStyle,
            hoverPaintStyle: endpointHoverStyle,
            connectorHoverStyle: connectorHoverStyle,
            maxConnections: -1,
            dragOptions: {},
            overlays: [
                [ "Label", {
                    location: [0.5, 1.5],
                    label: "Drag",
                    cssClass: "endpointSourceLabel",
                    visible:false
                } ]
            ]
        },
        // the definition of target endpoints (will appear when the user drags a connection)
        targetEndpoint = {
            endpoint: "Dot",
            paintStyle: { fill: "#61B7CF", radius: 5 },
            hoverPaintStyle: endpointHoverStyle,
            maxConnections: -1,
            dropOptions: { hoverClass: "hover", activeClass: "active" },
            isTarget: true,
            overlays: [
                [ "Label", { location: [0.5, -0.5], label: "Drop", cssClass: "endpointTargetLabel", visible:false } ]
            ]
        };
    //渲染函数
    var _addEndpoints = function (toId, sourceAnchors, targetAnchors) {
        for (var i = 0; i < sourceAnchors.length; i++) {
            var sourceUUID = toId + sourceAnchors[i];
            instance.addEndpoint(toId, sourceEndpoint, {
                anchor: sourceAnchors[i], uuid: sourceUUID
            });
        }
        for (var j = 0; j < targetAnchors.length; j++) {
            var targetUUID = toId + targetAnchors[j];
            instance.addEndpoint(toId, targetEndpoint, { anchor: targetAnchors[j], uuid: targetUUID });
        }
    };
    //连线事件
    instance.bind("connection", function (connInfo, originalEvent) {
        showModel();
    });
    function GetQueryString(name) {
        var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if(r!=null)
            return  decodeURI(r[2]);
        return null;
    }
    var CreatHtml = function (jsonData) {//生成算法组件标签
        var modellist = document.getElementById("modellist");
        for (var a = 0; a < jsonData.category.length; a++) {
            modellist.innerHTML +=
                '<div class="modellist_one">' +
                '<div class="modellist_name" id ="categoryId_' + jsonData.category[a].categoryId + '">' + jsonData.category[a].categoryName + '</div>' +
                '<div class="modellist_content" id="nameCategoryId_' + jsonData.category[a].categoryId + '"></div>' +
                '</div>';
        }
      /*  modellist.innerHTML +=
            '<div class="modellist_one">' +
            '<div class="modellist_name" id ="nestCategory">嵌套模型</div>' +
            '<div class="modellist_content" id="nameNestCategory"></div>' +
            '</div>';*/
        for (var n = 0; n < jsonData.algorithm.length; n++) {
            var sorts = jsonData.algorithm[n].categoryId.split(",");
            for(var o=0; o<sorts.length; o++){
                var algorithm = document.getElementById("nameCategoryId_" + sorts[o]);
                if(algorithm!=null)
                    algorithm.innerHTML +=
                        '<div class="iconitems iconitemsRectangle icontinside" icontype="uiAlgorithm" id="1_' + jsonData.algorithm[n].algorithmId + '">' +
                            '<input type="hidden" class="paramNum" value="'+jsonData.algorithm[n].paramNum+'">'+
                            '<span class="iconitems-span" title="' + jsonData.algorithm[n].algorithmName + '">' + jsonData.algorithm[n].algorithmName + '</span>' +
                        '</div>';
            }
        }
        //嵌套模型
        // for (var m = 0; m < jsonData.model.length; m++) {
        //     var model = document.getElementById("nameNestCategory");
        //     model.innerHTML +=
        //         '<div class="iconitems iconitemsRectangle icontinside" icontype="uiNestModel" id="0_'+ jsonData.model[m].id +'">' +
        //             '<span class="iconitems-span">' + jsonData.model[m].modelName + '</span>' +
        //             '<input type="hidden" id="modelJson_' + jsonData.model[m].id + '" value="' + jsonData.model[m].json + '">'+
        //         '</div>';
        // }
    }
    var loadHtml = function (loadjsondata) {
        var load_jsondata = loadjsondata.result[0].json;
        $("#modelIntroduction").val(loadjsondata.result[0].introduction);
        $("#modelName").val(loadjsondata.result[0].name);
        $("#modelIsreuse").val(loadjsondata.result[0].isReuse);
        loadModel(load_jsondata);
    }
    //加载组件
    $.ajax({
        url:constUrl+"ws/model",
        type:'post',
        data:{
            "operateType":"categoryList"
        },
        dataType:'json',
        success: function(responseText) {
            var jsondata = responseText;
            CreatHtml(jsondata);
            //绑定组件拖曳事件
            var iconitems = $(".iconitems");
            iconitems.draggable({
                zIndex: 999,
                helper: function(){
                    //创建一个可拖动的框
                    if($(this).attr("icontype")=="uiStart"||$(this).attr("icontype")=="uiEnd"){
                        var clone = $('<div class="iconitems iconitemsCircle ui-draggable ui-draggable-handle ui-dragging" icontype="'+$(this).attr("icontype")+'" dataid="'+$(this).attr("id")+'">' + $(this).html() + '</div>');
                    }
                    else{
                        var clone = $('<div class="iconitems iconitemsRectangle ui-draggable ui-draggable-handle ui-dragging" icontype="'+$(this).attr("icontype")+'" dataid="'+$(this).attr("id")+'">' + $(this).html() + '</div>');
                    }
                    clone.appendTo('body');
                    return clone;
                },
                containment: 'body',
                scope: 'topo'
            });
            content.droppable({
                scope: 'topo',
                drop: function (event, ui) {
                    var combination_left = $("#combination").position().left,
                        combination_top = $("#combination").position().top;
                    console.log("combination_left: "+combination_left+"; combination_top: "+combination_top)
                    var $this = $(this),
                        dragui = ui.draggable,
                        fatop = parseInt($this.offset().top),
                        faleft = parseInt($this.offset().left),
                        uitop = parseInt(ui.offset.top),
                        uileft = parseInt(ui.offset.left),
                        spantxt = dragui.children('span').text(),
                        paramnum = dragui.children('.paramNum').val(),
                        uid = dragui.attr('icontype'),
                        dataid = dragui.attr('id'),
                        alluid = $("#combination").children('div.' + uid);
                    var allicon = alluid.length+1,
                        idnum = 1,
                        idArr  = new Array;
                    idArr.push(0);
                    alluid.each(function(i) {
                        idArr.push(parseInt($(this).attr('id').split('_')[1]));
                    });
                    idArr.sort(function(a,b){return a>b?1:-1});
                    for(var i = 0; i < allicon; i++){
                        var idArrOne = parseInt(idArr[i]);
                        if(i != idArrOne){
                            idnum = idArrOne - 1;
                            break;
                        }else{
                            idnum = allicon;
                        }
                    }
                    //插入元素组织
                    console.log("left: "+(uileft - faleft - combination_left)+"; top: "+(uitop - fatop - combination_top))
                    var newstyle = 'left:' + (uileft - faleft - combination_left) + 'px;top:' + (uitop - fatop - combination_top) + 'px',
                        newid = uid + '_' + idnum;
                    var newidnum;
                    if(idnum<10)
                        newidnum = "0"+idnum;
                    else
                        newidnum = idnum;
                    var isExist = true;
                    if(idnum!=1){
                        isExist = true;
                    }else{
                        isExist = false;
                    }
                    if(uid=="uiAlgorithm"){
                        var str =
                            '<div class="'+uid+' uibox" id='+newid+' style='+newstyle+' dataid="'+dataid+'">' +
                            '<div class="uidiv"> ' +
                            '<span class="glyphicon glyphicon-edit modelAlgorithmSetting fleft left5"></span> ' +
                            '<span class="glyphicon glyphicon-remove fright right5"></span> ' +
                            '</div>' +
                            '<div class="uitext" title="'+ spantxt +'">' + newidnum + ":" + spantxt + '</div>' +
                            '<input type="hidden" class="paramNum" id="'+newid+'paramNum" value="'+paramnum+'"/>'+
                            '<input type="hidden" class="paramsConfig" id="' + newid + 'params" value=""/>' +
                            '<input type="hidden" class="inputConfig" id="' + newid + 'input" value=""/>' +
                            '</div>';
                    } else if(uid=="uiNestModel") {
                        var str =
                            '<div class="'+uid+' uibox" id='+newid+' style='+newstyle+' dataid="'+dataid+'">' +
                            '<div class="uidiv"> ' +
                            '<span class="glyphicon glyphicon-edit modelAlgorithmSetting fleft left5"></span> ' +
                            '<span class="glyphicon glyphicon-remove fright right5"></span> ' +
                            '</div>' +
                            '<div class="uitext" title="'+ spantxt +'">' + newidnum + ":" + spantxt + '</div>' +
                            '<input type="hidden" class="paramsConfig" id="' + newid + 'params" value=""/>' +
                            '<input type="hidden" class="inputConfig" id="' + newid + 'input" value=""/>' +
                            '</div>';
                    } else if(uid=="uiData"){
                        var str =
                            '<div class="'+uid+' uibox" id='+newid+' style='+newstyle+'>' +
                            '<div class="uidiv"> ' +
                            '<span class="glyphicon glyphicon-edit modelDataRename fleft left5"></span> ' +
                            '<span class="glyphicon glyphicon-remove fright right5"></span> ' +
                            '</div>' +
                            '<div class="uitext" id="'+newid+'_text" title="' + spantxt + idnum +'">' + spantxt + idnum + '</div>' +
                            '</div>';
                    } else{
                        if(isExist&&(uid=="uiStart"||uid=="uiEnd")){
                            var str = "";
                            layer.alert("您不能创建多个开始或结束！");
                        }else {
                            var str =
                                '<div class="'+uid+' uibox" id='+newid+' style='+newstyle+'>' +
                                '<div class="uitext uimid">'+spantxt+'</div>' +
                                '</div>';
                        }
                    }
                    combination.append(str);
                    //渲染，根据不同标签类型进行渲染(添加连接点)
                    if(uid=="uiStart"){
                        if(!isExist){
                            _addEndpoints(newid, ["RightMiddle"], []);
                            instance.draggable(instance.getSelector("#combination .uibox"));
                        }
                    }
                    else if(uid=="uiEnd"){
                        if(!isExist) {
                            _addEndpoints(newid, [], ["LeftMiddle"]);
                            instance.draggable(instance.getSelector("#combination .uibox"));
                        }
                    }
                    else if(uid=="uiData"){
                        _addEndpoints(newid, ["RightMiddle"], []);
                        instance.draggable(instance.getSelector("#combination .uibox"));
                    }
                    else{
                        _addEndpoints(newid, ["RightMiddle"], ["LeftMiddle"]);
                        instance.draggable(instance.getSelector("#combination .uibox"));
                    }
                    showModel();
                }
            });
        },
        complete: function() {},
        error: function() {}
    })
    var url_modelId =  GetQueryString("modelId");
    if(url_modelId!=null){
        console.log(url_modelId)
        var modelid = document.getElementById("modelId");
        modelid.value = url_modelId;
        //加载具体model
        $.ajax({
            url:constUrl+"ws/model",
            type:'post',
            data:{
                "operateType":"showDetail",
                "modelId":url_modelId
            },
            dataType:'json',
            success: function(responseText) {
                var jsondata = responseText;
                loadHtml(jsondata);
            },
            complete: function() {},
            error: function() {}
        });
    }
    //删除节点
    $(combination).on("click", ".glyphicon-remove", function() {
        var one = $(this);
        layer.confirm('确认删除该节点及其连线？', {
            btn: ['确认','取消'] //按钮
        }, function(){
            var delid = one.parent().parent().attr("id");
            instance.remove(delid);
            layer.msg('删除成功！', {icon: 1,time:2000});
            showModel();
        }, function(){

        });
    });
    //编辑详细参数
    $(combination).on("click", ".modelAlgorithmSetting", function () {
        var $this = $(this).parent().parent();
        document.getElementById('blockid').value = $this.attr("id");
        document.getElementById('algorithmid').value = $this.attr("dataid").split("_")[1];
        var frontAlgorithmIds = [];
        var algorithmid = "";
        var blockName = "";
        $.each(instance.getAllConnections(), function (idx, connection) {
            algorithmid = "";
            if(connection.targetId == document.getElementById('blockid').value){
                $("#combination .uibox").each(function (idx, elem) {
                    var $elem = $(elem);
                    if(connection.sourceId==$elem.attr('id')&&$elem.attr('dataId')!=null){
                        algorithmid = $elem.attr('dataId').split("_")[1];
                        blockName = $elem.children('.uitext').text();
                    }
                });
                frontAlgorithmIds.push({
                    blockId: connection.sourceId,
                    blockName: blockName,
                    algorithmId: algorithmid,
                });
            }
        });
        var qz_jsonData = JSON.stringify(frontAlgorithmIds);
        $("#frontAlgorithmIds").val(qz_jsonData);
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '算法配置',
            fix: false,
            scrollbar: false,
            shadeClose: true,
            maxmin: true,
            area: ['500px', '700px'],
            content: constUrl+'views/model/edit/algorithm/set.action'
        });
    });
    //外部数据源重命名
    $(combination).on("click", ".modelDataRename", function () {
        var $this = $(this).parent().parent();
        document.getElementById('blockid').value = $this.attr("id");
        layer.open({
            type: 2,
            skin: 'layui-layer-lan',
            title: '外部数据源重命名',
            fix: false,
            scrollbar: false,
            shadeClose: true,
            maxmin: true,
            area: ['500px', '350px'],
            content: constUrl+'views/model/edit/data/rename.action'
        });
    });
    //展示
    var jsondata = '';
    var showModel = function () {
        var connects = [];
        $.each(instance.getAllConnections(), function (idx, connection) {
            connects.push({
                pageSourceId: connection.sourceId,
                pageTargetId: connection.targetId
            });
        });
        var blocks = [];
        $("#combination .uibox").each(function (idx, elem) {
            var $elem = $(elem);
            if($elem.attr('dataid')!=null){
                blocks.push({
                    dataId: $elem.attr('dataid').split("_")[1],
                    isAlgorithm: $elem.attr('dataid').split("_")[0],
                    blockId: $elem.attr('id'),
                    blockClass: $elem.attr('class').split(' ')[0],
                    blockName: $elem.children('.uitext').text(),
                    blockTitle: $elem.children('.uitext').attr("title"),
                    blockX: parseInt($elem.css("left")),
                    blockY: parseInt($elem.css("top")),
                    paramNum: $elem.children('.paramNum').val(),
                    inputConfig: eval($elem.children('.inputConfig').val()),
                    paramsConfigDefault: eval($elem.children('.paramsConfig').val())
                });
            }else{
                blocks.push({
                    blockId: $elem.attr('id'),
                    blockClass: $elem.attr('class').split(' ')[0],
                    blockName: $elem.children('.uitext').text(),
                    blockX: parseInt($elem.css("left")),
                    blockY: parseInt($elem.css("top"))
                });
            }
        });
        jsondata = "组件:\n" + JSON.stringify(blocks, null, 2) + "\n连线:\n" + JSON.stringify(connects, null, 2);
        $('#json_content').text(jsondata);
    }
    //保存
    var saveBtn = $('#saveBtn');
    saveBtn.click(function() {
        var lackAlgorithm = true;
        var lackStart = true;
        var lackEnd = true;
        var lackParamsConfig = false;
        var isCreate = $("#modelId").val();
        var connects = [];
        $.each(instance.getAllConnections(), function (idx, connection) {
            connects.push({
                pageSourceId: connection.sourceId,
                pageTargetId: connection.targetId
            });
        });
        var blocks = [];
        $("#isNesting").val("0");
        $("#combination .uibox").each(function (idx, elem) {
            var $elem = $(elem);
            if($elem.attr('dataid')!=null){
                var inco = $elem.children('.inputConfig').val(),
                    paco = $elem.children('.paramsConfig').val(),
                    paramNum = $elem.children('.paramNum').val();
                if($elem.attr('dataid').split("_")[0]=="0"){
                    $("#isNesting").val("1");
                }
                if(paco==""&&paramNum!=0){
                    lackParamsConfig = true;
                }
                lackAlgorithm = false;
                blocks.push({
                    dataId: $elem.attr('dataid').split("_")[1],
                    isAlgorithm: $elem.attr('dataid').split("_")[0],
                    blockId: $elem.attr('id'),
                    blockClass: $elem.attr('class').split(' ')[0],
                    blockName: $elem.children('.uitext').text(),
                    blockTitle: $elem.children('.uitext').attr("title"),
                    blockX: parseInt($elem.css("left")),
                    blockY: parseInt($elem.css("top")),
                    paramNum: paramNum,
                    inputConfig: eval(inco),
                    paramsConfigDefault: eval(paco),
                    cpuNum: 0
                });
            }else{
                if($elem.children('.uitext').text()=="开始"){
                    lackStart=false;
                }
                if($elem.children('.uitext').text()=="结束"){
                    lackEnd=false;
                }
                blocks.push({
                    blockId: $elem.attr('id'),
                    blockClass: $elem.attr('class').split(' ')[0],
                    blockName: $elem.children('.uitext').text(),
                    blockX: parseInt($elem.css("left")),
                    blockY: parseInt($elem.css("top"))
                });
            }
        });
        var post_jsondata = "{\"blocks\":"+JSON.stringify(blocks)+",\"lines\":"+JSON.stringify(connects)+",\"taskNumber\":\"1\"}";
        $("#post_jsonData").val(post_jsondata);
        var datas = [];
        $.each(instance.getAllConnections(), function (idx, connection) {
            if(connection.sourceId.split("_")[0] == "uiData"){
                $("#combination .uibox").each(function (idx, elem) {
                    var $elem = $(elem);
                    if(connection.targetId==$elem.attr('id')&&$elem.attr('dataId')!=null){
                        var data = $elem.children(".inputConfig").val();
                        var json_data = eval("("+data+")");
                        for(var i=0; i<json_data.length; i++){
                            if(JSON.stringify(json_data[i].frontOutput.frontOutputName.split("+")[1])!=""&&JSON.stringify(json_data[i].frontOutput.frontOutputName.split("+")[1])!="undefined"&&json_data[i].frontOutput.frontOutputName.split("+")[1]!=null){
                                datas.push({
                                    dataName: json_data[i].frontOutput.frontOutputName.split("+")[0],
                                    dataBlockId: json_data[i].frontOutput.frontOutputName.split("+")[1],
                                    dataNumber: json_data[i].frontOutput.frontOutputName.split("+")[2],
                                    Name: $("#"+connection.sourceId).children(".uitext").html()
                                });
                            }
                        }
                    }
                });
            }
        });
        $("#datas").val(JSON.stringify(datas));
        var endAlgorithmIds = [];
        var algorithmid = "";
        var blockName = "";
        $.each(instance.getAllConnections(), function (idx, connection) {
            algorithmid = "";
            if(connection.targetId == "uiEnd_1"){
                $("#combination .uibox").each(function (idx, elem) {
                    var $elem = $(elem);
                    if(connection.sourceId==$elem.attr('id')&&$elem.attr('dataId')!=null){
                        algorithmid = $elem.attr('dataId').split("_")[1];
                        blockName = $elem.children('.uitext').text();
                    }
                });
                endAlgorithmIds.push({
                    blockId: connection.sourceId,
                    blockName: blockName,
                    algorithmId: algorithmid
                });
            }
        });
        var end_jsonData = JSON.stringify(endAlgorithmIds);
        $("#endAlgorithmIds").val(end_jsonData);
        algorithmid = "";
        blockName = "";
        var startAlgorithmIds = [];
        $.each(instance.getAllConnections(), function (idx, connection) {
            if(connection.sourceId == "uiStart_1"){
                $("#combination .uibox").each(function (idx, elem) {
                    var $elem = $(elem);
                    if(connection.targetId==$elem.attr('id')&&$elem.attr('dataId')!=null){
                        algorithmid = $elem.attr('dataId').split("_")[1];
                        blockName = $elem.children('.uitext').text();
                    }
                });
                startAlgorithmIds.push({
                    blockId: connection.targetId,
                    blockName: blockName,
                    algorithmId: algorithmid
                });
            }
        });
        var start_jsonData = JSON.stringify(startAlgorithmIds);
        $("#startAlgorithmIds").val(start_jsonData);
        if(lackParamsConfig){
            layer.alert("算法详细信息尚未配置完成，保存模型失败！");
        }else if(lackAlgorithm){
            layer.alert("至少需要选择一个算法！");
        }else if(lackStart){
            layer.alert("请在工作流中加入开始节点！");
        }else if(lackEnd){
            layer.alert("请在工作流中加入结束节点！");
        }else{
            if(isCreate==""){
                //layer弹出
                layer.ready(function() {
                    layer.open({
                        type: 2,
                        skin: 'layui-layer-lan',
                        title: '模型注册',
                        fix: false,
                        scrollbar: false,
                        shadeClose: true,
                        maxmin: true,
                        area: ['500px', '700px'],
                        content: constUrl+'views/model/edit/save.action'
                    });
                });
            } else{
                layer.ready(function() {
                    layer.open({
                        type: 2,
                        skin: 'layui-layer-lan',
                        title: '模型修改',
                        fix: false,
                        scrollbar: false,
                        shadeClose: true,
                        maxmin: true,
                        area: ['500px', '370px'],
                        content: constUrl+'views/model/edit/alert.action'
                    });
                });
            }
        }
    });
    //加载
    var loadModel = function (json) {
        var lines = json.lines,
            blocks = json.blocks,
            htmlText = "";
        for (var i = 0; i < blocks.length; i++) {
            var viewstyle = 'left:' + blocks[i].blockX + 'px;top:' + blocks[i].blockY + 'px;',
                viewdataid = blocks[i].isAlgorithm + "_" + blocks[i].dataId,
                viewid = blocks[i].blockId,
                viewClass = blocks[i].blockClass,
                viewName = blocks[i].blockName,
                viewTitle = blocks[i].blockTitle,
                viewParamNum = blocks[i].paramNum,
                viewInput = JSON.stringify(blocks[i].inputConfig),
                viewValue = JSON.stringify(blocks[i].paramsConfigDefault);
            if (viewClass == "uiAlgorithm") {
                htmlText = htmlText +
                    '<div class="' + viewClass + ' uibox" id=' + viewid + ' style=' + viewstyle + ' dataid="' + viewdataid + '">' +
                    '<div class="uidiv"> ' +
                    '<span class="glyphicon glyphicon-edit modelAlgorithmSetting fleft left5"></span> ' +
                    '<span class="glyphicon glyphicon-remove fright right5"></span> ' +
                    '</div>' +
                    '<div class="uitext" title="'+ viewTitle +'">' + viewName + '</div>' +
                    '<input type="hidden" class="paramNum" id="'+viewid+'paramNum" value=\''+viewParamNum+'\'/>'+
                    '<input type="hidden" class="paramsConfig" id="' + viewid + 'params" value=\'' + viewValue + '\'/>' +
                    '<input type="hidden" class="inputConfig" id="' + viewid + 'input" value=\'' + viewInput + '\'/>' +
                    '</div>';
            } else if(viewClass == "uiNestModel"){
                htmlText = htmlText +
                    '<div class="' + viewClass + ' uibox" id=' + viewid + ' style=' + viewstyle + ' dataid="' + viewdataid + '">' +
                    '<div class="uidiv"> ' +
                    '<span class="glyphicon glyphicon-edit modelAlgorithmSetting fleft left5"></span> ' +
                    '<span class="glyphicon glyphicon-remove fright right5"></span> ' +
                    '</div>' +
                    '<div class="uitext" title="'+ viewTitle +'">' + viewName + '</div>' +
                    '<input type="hidden" class="paramsConfig" id="' + viewid + 'params" value=\'' + viewValue + '\'/>' +
                    '<input type="hidden" class="inputConfig" id="' + viewid + 'input" value=\'' + viewInput + '\'/>' +
                    '</div>';
            } else if(viewClass == "uiData"){
                htmlText = htmlText +
                    '<div class="' + viewClass + ' uibox" id=' + viewid + ' style=' + viewstyle + ' dataid="' + viewdataid + '">' +
                    '<div class="uidiv"> ' +
                    '<span class="glyphicon glyphicon-edit modelDataRename fleft left5"></span> ' +
                    '<span class="glyphicon glyphicon-remove fright right5"></span> ' +
                    '</div>' +
                    '<div class="uitext uimid" title="'+ viewName +'">' + viewName + '</div>' +
                    '</div>';
            } else {
                htmlText = htmlText + '<div class="' + viewClass + ' uibox" id=' + viewid + ' style=' + viewstyle + '><div class="uitext uimid">' + viewName + '</div></div>';
            }
        };
        combination.append(htmlText);
        //渲染连接点
        $("#combination .uibox").each(function (idx, elem) {
            var $elem = $(elem),
                id = $elem.attr('id'),
                id_t = $elem.attr('id').split('_')[0];
            if(id_t=="uiStart"){
                _addEndpoints(id, ["RightMiddle"], []);
                instance.draggable(instance.getSelector("#combination .uibox"),{ containment: "parent"});
            }
            else if(id_t=="uiEnd"){
                _addEndpoints(id, [], ["LeftMiddle"]);
                instance.draggable(instance.getSelector("#combination .uibox"),{ containment: "parent"});
            }
            else if(id_t=="uiData"){
                _addEndpoints(id, ["RightMiddle"], []);
                instance.draggable(instance.getSelector("#combination .uibox"),{ containment: "parent"});
            }
            else{
                _addEndpoints(id, ["RightMiddle"], ["LeftMiddle"]);
                instance.draggable(instance.getSelector("#combination .uibox"),{ containment: "parent"});
            }
        });
        for (var i = 0; i < lines.length; i++) {
            var PageSourceId = lines[i].pageSourceId + "RightMiddle",
                PageTargetId = lines[i].pageTargetId + "LeftMiddle";
            instance.connect({uuids: [PageSourceId, PageTargetId], editable: true});
        }
        showModel();
    }
    //动态隐藏json显示栏
    $("#json_content_control").click(function(){
        $("#json_content").slideToggle("slow");
    });
    //动态显示组件栏
    var modellist = document.getElementById('modellist');
    modellist.addEventListener('click', function(ev){
        var ev = ev || window.event;
        var target = ev.target || ev.srcElement;
        if(target.id.split('_')[0] == 'categoryId'){
            var idvalue = target.id.split('_')[1];
            $("#nameCategoryId_"+idvalue).slideToggle("slow");
        }
    });
});